//
//  FFWalletTradeRecordVM.m
//  LLWallet
//
//  Created by tt on 2020/9/7.
//

#import "FFWalletTradeRecordVM.h"
#import "FFWalletTradeRecordCell.h"

@interface FFWalletTradeRecordVM ()

@property(nonatomic,strong) NSMutableArray<FFWalletTradeRecordResp*> *items;

@property(nonatomic,assign) NSInteger pageIndex;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,assign) BOOL hasMore; // 是否还有更多数据

@end

@implementation FFWalletTradeRecordVM

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.pageIndex = 1;
        self.pageSize = [WKApp shared].config.pageSize;
        self.hasMore = true;
        self.items = [NSMutableArray array];
    }
    return self;
}

- (NSArray<NSDictionary *> *)tableSectionMaps {
    if(!self.items || self.items.count<=0) {
        return nil;
    }
    NSMutableArray<NSDictionary*> *itemMapArray = [NSMutableArray array];
    for (FFWalletTradeRecordResp *resp in self.items) {
        [itemMapArray addObject:@{
            @"class": FFWalletTradeRecordModel.class,
            @"title": resp.title?:@"",
            @"amount":@(resp.amount),
            @"balance": @(resp.balance),
            @"time": resp.createdAt?:@"",
        }];
    }
    return @[
        @{
            @"height":@(0.01f),
            @"items":itemMapArray
        },
    ];
}


-(void)requestData:(void (^)(NSError * _Nullable))complete {
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"impay/wallet/records" parameters:@{@"page_index":@(self.pageIndex),@"page_size":@(self.pageSize)} model:FFWalletTradeRecordResp.class].then(^(NSArray<FFWalletTradeRecordResp*> *items){
        [weakSelf.items addObjectsFromArray:items];
        if(items && items.count>=self.pageSize) {
            self.hasMore = true;
        }else {
            self.hasMore = false;
        }
         complete(nil);
       
    }).catch(^(NSError *error){
        complete(error);
    });
}


- (void)pullup:(void (^)(BOOL))complete {
    if(!self.hasMore) {
        complete(self.hasMore);
        return;
    }
    self.pageIndex ++;
    [self requestData:^(NSError * _Nullable error) {
        complete(self.hasMore);
    }];
}

- (BOOL)enablePullup {
    return YES;
}

@end

@implementation FFWalletTradeRecordResp

+ (WKModel *)fromMap:(NSDictionary *)dictory type:(ModelMapType)type {
    FFWalletTradeRecordResp *resp = [FFWalletTradeRecordResp new];
    resp.recordID = dictory[@"record_id"];
    resp.createdAt = dictory[@"created_at"];
    resp.amount = [dictory[@"amount"] integerValue];
    resp.balance = [dictory[@"balance"] integerValue];
    resp.title = dictory[@"title"];
    resp.remark = dictory[@"remark"];
    return resp;
}

@end
